package cn.itsource.user.service.impl;

import cn.itsource.basic.SystemContents;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.utils.MD5Utils;
import cn.itsource.basic.utils.RedisUtils;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.vo.UserVO;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    /*
        2.后台的数据验证
        3.密码明文存储的问题（加密处理）
        4.存储到数据库
     */
    @Override
    public void regUser(UserVO userVO) {
        //验证数据
        checkUserVO(userVO);
        //把UserVO对象转换为User对象
        User user= userVOToUser(userVO);
        super.save(user);
    }

    //登录的逻辑

    /**
     *
     * @param username
     * @param pwd   用户登录输入的明文密码   应该和  查询出来的对象里面的 密码比较
     * @return
     */
    @Override
    public User loginByUserName(String username, String pwd) {
        //去数据库查询数据、
        User user = userMapper.login(username,1 );
        if (user==null){
            throw  new RuntimeException("用户名或密码错误");
        }
        //比较密码
        //1.明文加密
        String md5Str = MD5Utils.encrypByMd5(pwd + user.getSalt());
        //比较密文
        if (!md5Str.equals(user.getPassword())){
            throw  new RuntimeException("用户名或密码错误");
        }
        return  user;
    }

    private User userVOToUser(UserVO userVO) {
        User user = new User();
        user.setPhone(userVO.getPhone());
        user.setState(1);
        String salt = UUID.randomUUID().toString();
        //加密密码
        String md5 = MD5Utils.encrypByMd5(userVO.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        return  user;
    }


    //做数据验证
    private void checkUserVO(UserVO userVO) {
        //1.手机号是否注册
        User user = userMapper.getByPhone(userVO.getPhone());
        if (user!=null){
            throw new RuntimeException("手机号已经注册");
        }
        //2.验证验证码是否正确
        String redisCode = RedisUtils.INSTANCE.get(SystemContents.USER_REG + ":" + userVO.getPhone());
        if (redisCode==null){
            throw new RuntimeException("验证码不存在或已经过期");
        }
        if (redisCode!=null){
            String strCode = redisCode.split(":")[0];
            if(!userVO.getCode().equals(strCode)){
                throw new RuntimeException("验证码不正确");
            }
        }

        //3.两次密码是否一致
        if (!userVO.getPassword().equals(userVO.getPasswordRepeat())){
            throw new RuntimeException("两次密码不一致");
        }
    }
}
